package com.fzhucc.modules.security.util

import cn.hutool.http.HttpUtil
import com.alibaba.fastjson.JSON
import com.fzhucc.utils.dto.WxToken

/**
 * @author Woolsen
 * @since 2022/11/30 08:58
 */
object WxUtils {

    /**
     * 验证小程序code
     */
    fun authH5Code(appId: String, appSecret: String, code: String): WxToken {
        val result: String = HttpUtil.get(
            "https://api.weixin.qq.com/sns/oauth2/access_token", mapOf(
                "appid" to appId,
                "secret" to appSecret,
                "code" to code,
                "grant_type" to "authorization_code"
            )
        )
        val node = JSON.parseObject(result)
        if (node.containsKey("errcode")) {
            throw IllegalAccessError(node.getString("errmsg"))
        }
        return JSON.parseObject(result, WxToken::class.java)
    }


    /**
     * 验证小程序code
     */
    fun authMpCode(appId: String, appSecret: String, code: String): WxToken {
        val result: String = HttpUtil.get(
            "https://api.weixin.qq.com/sns/jscode2session", mapOf(
                "appid" to appId,
                "secret" to appSecret,
                "js_code" to code,
                "grant_type" to "authorization_code"
            )
        )
        val node = JSON.parseObject(result)
        if (node.containsKey("errcode")) {
            throw IllegalAccessError(node.getString("errmsg"))
        }
        return JSON.parseObject(result, WxToken::class.java)
    }
}